/**
  计算机等级考试-新增考试
*/
<template>
  <div class="operate-exam-container">
    <div style="height: 30px;">
      <el-breadcrumb style="float: left;" separator="/">
        <el-breadcrumb-item :to="{ path: '/computerExamsCreate' }">
        <span @click="reback()">{{ $t('mandarin.createExams') }}</span></el-breadcrumb-item>
        <el-breadcrumb-item v-if="operateMode === 'add'">{{ $t('common.btn.add') }}</el-breadcrumb-item>
        <el-breadcrumb-item v-if="operateMode === 'edit'">{{ $t('common.btn.edit') }}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button style="float:right; padding:0;" type="text" @click="reback()">{{ $t('common.btn.back') }}</el-button>
    </div>
    <el-card style="padding: 0!important;" shadow="never" v-loading="loading" body-style="padding: 24px;">
      <div slot="header">
        <div class="title" v-if="operateMode === 'add'">{{ $t('mandarin.addExam') }}</div>
        <div class="title" v-if="operateMode === 'edit'">{{ $t('mandarin.editExam') }}</div>
      </div>
      <el-form :model="examForm" label-position="right" class="exam-form" ref="examForm" label-width="110px">
        <el-row>
          <el-col :span="16">
            <el-form-item
              :label="$t('mandarin.contestTitle') + ':'"
              prop="title"
              :rules="[{ required: true, message: $t('mandarin.requireContestTitle'), trigger: 'blur' }, { validator: checkSpecial, trigger: 'blur'}]">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="examForm.title" :maxlength="64" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="$t('computerGrade.examType') + ':'"
              prop="typeId"
              :rules="[{ required: true, message: $t('computerGrade.requireExamType'), trigger: 'change' }]">
              <el-select style="width: 100%;" v-model="examForm.typeId" :placeholder="$t('common.pla.pleaseSelect')" @change="changeExamType" clearable>
                <el-option
                  v-for="item in options.typeId"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('subjectCompetitionBase.semester') + ':'" prop="calendarId"
              :rules="[{ required: true, message: $t('subjectCompetitionBase.requireSemester'), trigger: 'change'}]">
              <CalendarSelect v-model="examForm.calendarId"></CalendarSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="$t('mandarin.registrationStartTime') + ':'"
              prop="signUpStart"
              :rules="[{ required: true, message: $t('mandarin.requireRegisStartTime'), trigger: 'change'}]">
              <el-date-picker
                v-model="examForm.signUpStart"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :placeholder="$t('common.pla.pleaseSelect')"
                :picker-options="bmkssjPickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="$t('mandarin.registrationEndTime') + ':'"
              prop="signUpEnd"
              :rules="[{ required: true, message: $t('mandarin.requireRegistEndTime'), trigger: 'change'}]">
              <el-date-picker
                v-model="examForm.signUpEnd"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :placeholder="$t('common.pla.pleaseSelect')"
                :picker-options="bmjssjPickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="$t('computerGrade.limitSignCampus') + ':'"
              prop="lockLimit"
              :rules="[{ required: true, message: $t('computerGrade.requireLimitSignCampus'), trigger: 'change'}]">
                <el-radio v-model="examForm.lockLimit" label="1" @change="changeLockLimit">{{$t('computerGrade.limit')}}</el-radio>
                <el-radio v-model="examForm.lockLimit" label="0" @change="changeLockLimit">{{$t('computerGrade.notLimit')}}</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item
              :label="$t('computerGrade.campus') + ':'"
              prop="examCampusLimitList"
              ref="examCampusLimitList"
              :rules="campusValidateArray"
              class="campus-form-container">
                <el-checkbox-group v-model="examForm.examCampusLimitList">
                  <el-checkbox class="limit-campus-container" :disabled="examForm.lockLimit=='0'" v-for="(item, index) in options.examCampusLimitList" :key="item.value" :label="item.label">
                    <div class="limit-campus">{{ item.label }}</div>
                    <el-form-item
                      :prop="'limitNum ' + index"
                      :rules="campusNumValidateArray"
                      style="display: inline-block">
                        <span>{{ $t('computerGrade.limitPeople') }}</span>
                        <span><el-input v-model="item.limitNum" :disabled="examForm.lockLimit=='0'" :maxlength="4" clearable></el-input></span>
                      </el-form-item>
                  </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="$t('computerGrade.conflictExamType') + ':'"
              >
                <el-checkbox-group v-model="examForm.conflictType" class="limit-container">
                  <el-checkbox v-for="item in options.conflictType" :key="item.key" :label="item.label">
                    {{ item.label }}
                  </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="8">
            <el-form-item
              :label="$t('computerGrade.registObject') + ':'"
              prop="listSet"
              :rules="[{ required: true, message: $t('computerGrade.requireRegistObject'), trigger: 'change'}, { validator: checkListSet, trigger: 'change'}]">
              <el-button style="line-height: 10px;" type="text" size="medium" @click="listSetting()">{{ $t('mandarin.listSet') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div class="operate-btn-container">
        <div class="float-right">
          <el-button @click="cancelOperate()">{{ $t('common.btn.cancel') }}</el-button>
          <el-button type="primary" @click="confirmOperate()">{{ $t('common.btn.confirm') }}</el-button>
        </div>
      </div>
    </el-card>
    <!-- <el-dialog
      :before-close="beforeClose"
      :title="$t('mandarin.listSet')"
      width="70%"
      class="examination-dialog"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <list-setting ref="addListSet"
        v-if="operateMode === 'add'"
        :addConfirmData="addConfirmData"
        @close-list-setting="beforeClose"
        @confirm-list-setting="confirmAddListSetting">
      </list-setting>
      <edit-list-setting ref="editListSet" v-if="operateMode === 'edit'"
        :editConfirmData="editConfirmData"
        @close-list-setting="beforeClose"
        @confirm-list-setting="confirmEditListSetting"
        @delete-list-setting="deleteListSetting">
      </edit-list-setting>
    </el-dialog> -->
  </div>
</template>

<script>
import UTILS from "common/src/utils/utils";
// import listSetting from './listSetting';
// import editListSetting from './editListSetting';
import { queryDic } from "common/src/api/dictionary";
import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
export default {
  components: {
    // 'list-setting': listSetting,
    // 'edit-list-setting': editListSetting
  },
  data() {
    return {
      examForm: {
        title: '',
        typeId: '',
        calendarId: '',
        signUpStart: '',
        signUpEnd: '',
        lockLimit: '',
        examCampusLimitList: [],
        conflictType: [],
        listSet: '',
      },
      options: {
        typeId: [],
        examCampusLimitList: [
          {
            key: '1',
            label: '四平路校区',
            limitNum: '',
            value: '1'
          },
          {
            key: '3',
            label: '嘉定校区',
            limitNum: '',
            value: '3'
          },
        ],
        conflictType: []
      },
      toolbar:['undo redo | styleselect | fontselect | formatselect | fontsizeselect | forecolor backcolor | bold italic underline strikethrough | table | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist |  fullscreen '],
      dialogVisible: false,
      campusValidateArray: [],
      campusNumValidateArray: [],
      addConfirmData: [],
      editConfirmData: [],
      deleteIdList: []
    }
  },
  props: {
    operateMode: {
      type: Object,
      default: () => {}
    },
    operateData: {
      type: Object,
      default: () => {}
    },
    rows: {
      type: Object,
      default: () => {}
    },
  },
  computed: {
    bmkssjPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.examForm.signUpEnd) {
            // 报名开始时间必须小于报名截止时间
            if (value.getTime() > new Date(_this.examForm.signUpEnd.split(' ')[0]).getTime()) {
              return true
            }
          }
          return false
        }
      }
    },
    bmjssjPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.examForm.signUpStart) {
            // 评分截止时间必须大于评分开始时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.examForm.signUpStart.split(' ')[0]).getTime()) {
              return true
            }
          }
          return false
        }
      }
    }
  },
  created() {
    this.initOptions()
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('subjectCompetitionBase.specialText')))
      } else {
        callback()
      }
    },
    // 校验名单
    checkListSet(rule, value, callback) {
      if (!value || (value.length && value.length === 0)) {
        callback(new Error(this.$t('computerGrade.requireRegistObject')))
      } else {
        callback()
      }
    },
    async initOptions() {
      // 查询考试类型字典
      const response = await subjectCompetitionApi.computerExamTypeListNoPage({
        "educationTag": 1,
        "subjectType": 1,
        "isEnabled": 1
      })
      if (response.code === 200 && response.data.length > 0) {
        response.data.forEach(item => {
          this.options.typeId.push({
            key: item.id,
            label: item.competitionType,
            value: item.id
          })
        })
        if (this.operateMode === 'add') {
          this.options.conflictType = this.options.typeId
        }
      }
    },
    // 修改考试类型
    async changeExamType(val) {
      this.options.conflictType = []
      if (!val) {
        const resp = await subjectCompetitionApi.computerExamTypeListNoPage({
          "educationTag": 1,
          "subjectType": 1,
          "isEnabled": 1
        })
        if (resp.code === 200 && resp.data.length > 0) {
          resp.data.forEach(item => {
            this.options.conflictType.push({
              key: item.id,
              label: item.competitionType,
              value: item.id
            })
          })
        }
      } else {
        const res = await subjectCompetitionApi.computerExamTypeListNoPage({
          "educationTag": 1,
          "subjectType": 1,
          "excludeId": val,
          "isEnabled": 1
        })
        if (res.code === 200 && res.data.length > 0) {
          res.data.forEach(item => {
            this.options.conflictType.push({
              key: item.id,
              label: item.competitionType,
              value: item.id
            })
          })
        }
      }
    },
    reback() {
      this.$emit('change-exam-create-index')
    },
    // 名单设置
    // listSetting() {
    //   this.dialogVisible = true
    // },
    // 取消操作
    cancelOperate() {
      this.$emit('change-exam-create-index')
    },
    // 确认操作
    confirmOperate() {
      this.$refs['examForm'].validate(async valid => {
        if (valid) {

            if(this.operateMode === 'edit'){
              let endTime = new Date(this.rows.signUpEnd.replace('-', '/')).getTime()
              let nowTimeResponse = await graduateStudentApi.getCurrentSystemTime()
              if (nowTimeResponse.data) {
                nowTimeResponse.data = new Date(nowTimeResponse.data).getTime()
              }
              if (!(nowTimeResponse.data <= endTime)) {
                this.$eduConfirm(this.$t('mandarin.registEndTime') + '（' + this.rows.signUpEnd + '）已过').then(_ => {})
                return
              }
            }

          if (this.examForm.signUpStart > this.examForm.signUpEnd) {
            this.$eduAlert(this.$t('mandarin.validateRegistTime'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          let examCampusLimitList = []
          this.options.examCampusLimitList.map((item, index) => {
            if (item.limitNum) {
              examCampusLimitList.push({
                "limitCampus": item.value,
                "limitNum": item.limitNum
              })
            }
          })
          let conflictType = []
          this.options.conflictType.map((item, index) => {
            this.examForm.conflictType.map(element => {
              if (item.label === element) {
                conflictType.push(item.key)
              }
            })
          })
          if (this.operateMode === 'add') {
            subjectCompetitionApi.computerCreateExam({
              "examCompetition": {
                "title": this.examForm.title,
                "signUpStartStr": this.examForm.signUpStart,
                "signUpEndStr": this.examForm.signUpEnd,
                "calendarId": this.examForm.calendarId,
                "examCategory": 3,
                "educationTag": 1,
                "typeId": this.examForm.typeId,
                "lockLimit": this.examForm.lockLimit,
                "conflictType": conflictType.join(',')
              },
              "examCampusLimitList": examCampusLimitList
            }).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: this.$t('subjectCompetitionBase.operateSuccessfully')
                })
                this.$emit('change-exam-create-index')
              }
            })
          } else {
            subjectCompetitionApi.computerModifyExam({
              "examCompetition": {
                "id": this.examForm.id,
                "title": this.examForm.title,
                "signUpStartStr": this.examForm.signUpStart,
                "signUpEndStr": this.examForm.signUpEnd,
                "calendarId": this.examForm.calendarId,
                "examCategory": 3,
                "educationTag": 1,
                "typeId": this.examForm.typeId,
                "lockLimit": this.examForm.lockLimit,
                "conflictType": conflictType.join(',')
              },
              "examCampusLimitList": examCampusLimitList,
            }).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: this.$t('subjectCompetitionBase.operateSuccessfully')
                })
                this.$emit('change-exam-create-index')
              }
            })
          }
        }
      })
    },
    // 新增-关闭按钮-关闭弹框
    beforeClose() {
      this.dialogVisible = false
      if (this.operateMode === 'add') {
        // this.$refs['addListSet'].cancelOperate()
        this.$refs['addListSet'].clearSereset()
      } else {
        // this.$refs['editListSet'].cancelOperate()
        this.$refs['editListSet'].clearSereset()
      }
    },
    // 新增-取消按钮-关闭弹框
    closeListSetting() {
      this.dialogVisible = false
      // if (this.operateMode === 'add') {
      //   // this.$refs['addListSet'].cancelOperate()
      //   this.$refs['addListSet'].clearSereset()
      // } else {
      //   // this.$refs['editListSet'].cancelOperate()
      //   this.$refs['editListSet'].clearSereset()
      // }
    },
    // 新增-确认按钮-确认名单
    confirmListSetting(val) {
      this.examForm.listSet = val.map(value => {
        return value.id
      })
      this.dialogVisible = false
      this.$refs.examForm.validateField('listSet')
    },
    // 校验限制人数
    checkLimitNum(rule, value, callback) {
      let _this = this
      let expReg = /^[1-9]\d*$/;
      let currentIndex = rule.field.split(' ')[1]
      let currentItem = _this.options.examCampusLimitList[currentIndex]
      if (!currentItem.limitNum && _this.examForm.examCampusLimitList.indexOf(currentItem.label) > -1) {
        callback(new Error(_this.$t('computerGrade.requireLimitNum')))
      } else if (currentItem.limitNum && _this.examForm.examCampusLimitList.indexOf(currentItem.label) > -1 && !expReg.test(currentItem.limitNum)) {
        callback(new Error(_this.$t('computerGrade.validateLimitNum')))
      } else {
        callback()
      }
    },
    // 校验校区
    checkCampus(rule, value, callback) {
      let _this = this
      let hasError = false
      for (let i = 0; i < this.options.examCampusLimitList.length; i++) {
        if (this.options.examCampusLimitList[i].limitNum == _this.examForm.examCampusLimitList[i]) {
          hasError = true
        }
      }
      if (value.length === 0 || !value) {
        callback(new Error(this.$t('computerGrade.requireLimitSignCampus')))
      } else if (hasError) {
        callback(new Error(this.$t('computerGrade.requireCampus')))
      } else {
        callback()
      }
    },
    // 修改限制报名校区
    changeLockLimit(val) {
      this.examForm.examCampusLimitList = []
      this.options.examCampusLimitList.forEach(el => {
        el.limitNum = ''
      })
      if (val === '1') {
        this.campusValidateArray = [{ required: true, validator: this.checkCampus, trigger: 'blur'}]
        this.campusNumValidateArray = [
          { required: true, validator: this.checkLimitNum, trigger: 'blur'}
        ]
      } else if (val === '0') {
        this.campusValidateArray = []
        this.campusNumValidateArray = []
        if (this.$refs.limitCampus) {
          this.$refs.limitCampus.clearValidate()
        }
      }
    },
    // 新增-确认按钮-确认名单
    confirmAddListSetting(val) {
      this.addConfirmData = val
      this.examForm.listSet = val.map(value => {
        return {
          studentId: value.studentId,
          studentName: value.name,
          sex: value.sex,
          grade: value.grade,
          sexI18n: value.sexI18n,
          college: value.faculty,
          collegeI18n: value.facultyI18n,
          atSchoolStatus: value.leaveSchool,
          atSchoolStatusI18n: value.leaveSchoolI18n,
          studentStatus: value.registrationStatus,
          studentStatusI18n: value.registrationStatusI18n,
          enrolMethods: value.enrolMethods,
          enrolMethodsI18n: value.enrolMethodsI18n,
          campus: value.campus,
          campusI18n: value.campusI18n
        }
      })
      this.dialogVisible = false
      this.$refs.examForm.validateField('listSet')
    },
    // 编辑-确认按钮-确认名单
    confirmEditListSetting(val) {
      this.editConfirmData = val
      this.examForm.listSet = val.map(value => {
        return {
          id: value.id,
          studentId: value.studentId,
          studentName: value.name,
          sex: value.sex,
          grade: value.grade,
          sexI18n: value.sexI18n,
          college: value.faculty,
          collegeI18n: value.facultyI18n,
          atSchoolStatus: value.leaveSchool,
          atSchoolStatusI18n: value.leaveSchoolI18n,
          studentStatus: value.registrationStatus,
          studentStatusI18n: value.registrationStatusI18n,
          enrolMethods: value.enrolMethods,
          enrolMethodsI18n: value.enrolMethodsI18n
        }
      })
      this.dialogVisible = false
      this.$refs.examForm.validateField('listSet')
    },
    deleteListSetting(val) {
      this.deleteIdList = val
    },
  },
  watch: {
    "operateData": {
      handler(newVal) {
        let _this = this
        if (this.operateMode === 'edit' || this.operateMode === 'details') {
          this.examForm = JSON.parse(JSON.stringify(newVal))
          this.changeLockLimit(this.examForm.lockLimit)
          this.examForm.examCampusLimitList = []
          this.editConfirmData = this.examForm.listSet
          if (newVal.examCampusLimitList && newVal.examCampusLimitList.length > 0) {
            newVal.examCampusLimitList.forEach(item => {
              if (item.limitCampus === '1') {
                this.examForm.examCampusLimitList.push('四平路校区')
                this.options.examCampusLimitList[0].limitNum = item.limitNum ? item.limitNum : ''
              } else if (item.limitCampus === '3') {
                this.examForm.examCampusLimitList.push('嘉定校区')
                this.options.examCampusLimitList[1].limitNum = item.limitNum ? item.limitNum : ''
              }
            })
          }
          if (this.examForm.typeId) {
            this.options.conflictType = []
            subjectCompetitionApi.computerExamTypeListNoPage({
              "educationTag": 1,
              "subjectType": 1,
              "excludeId": this.examForm.typeId,
              "isEnabled": 1
            }).then(res => {
              if (res.code === 200 && res.data.length > 0) {
                res.data.forEach(item => {
                  this.options.conflictType.push({
                    key: item.id,
                    label: item.competitionType,
                    value: item.id
                  })
                })
                if (this.examForm.conflictType.length>0) {
                  let conflictType = this.examForm.conflictType.split(',')
                  this.examForm.conflictType = []
                  conflictType.map(item => {
                    _this.options.conflictType.map(element => {
                      if (item === element.value.toString()) {
                        _this.examForm.conflictType.push(element.label)
                      }
                    })
                  })
                } else {
                  this.examForm.conflictType = []
                }
              }
            })
          }
          if (this.examForm.lockLimit==0) {
            this.examForm.examCampusLimitList = []
            this.options.examCampusLimitList.forEach(el => {
              el.limitNum = ''
            })
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy() {
    this.$refs['examForm'].resetFields()
  }
}
</script>
<style lang="scss" scoped>
  .operate-exam-container ::v-deep {
    .el-breadcrumb__item:last-child ::v-deep {
      .el-breadcrumb__inner {
        color: #606266;
        font-weight: bold;
        cursor: default
      }
    }
    .el-breadcrumb__item ::v-deep {
      .is-link {
        color: #aaa;
        font-weight: unset;
      }
      .is-link:hover {
        color: #409eff;
      }
    }
    .campus-form-container {
      .limit-campus {
        display: inline-block;
        width: 150px;
      }
      .el-checkbox-group ::v-deep {
        font-size: 14px;
        .el-checkbox {
          display: block;
        }
      }
      .el-checkbox-group :nth-child(2){
        margin-left: 0;
      }
    }
    .limit-container>label{
      margin-left: 0;
    }
    .exam-form {
      padding-right: 10px;
    }
    .exam-form ::v-deep {
      .el-date-editor.el-input {
        width: 100%!important;
      }
      .editor-custom-btn-container {
        display: none;
      }
    }
    .title {
      font-size: 18px;
    }
    .el-divider--horizontal {
      margin: 10px 0 20px 0 !important;
    }
    .operate-btn-container {
      border-top: 1px solid #ebeef5;
      padding: 20px;
      margin-bottom: 30px;
    }
  }

</style>
